/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ejb.LookupHelper;

/**
 *
 * @author Паша
 */
import javax.ejb.EJBException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class LookupHelper
{
	private static final Logger log = LoggerFactory.getLogger (LookupHelper.class);
	private static volatile LookupHelper instance;

	public static final LookupHelper getInstance ()
	{
		if (instance == null)
		{
			synchronized (LookupHelper.class)
			{
				if (instance == null) instance = new LookupHelper ();
			}
		}

		return instance;
	}

	private final InitialContext initialCtx;

	private LookupHelper ()
	{
		try{
			initialCtx = new InitialContext ();
		} catch (NamingException e)
		{
			throw new EJBException (e);
		}
	}

	public <T> T lookup (String name) throws NamingException
	{
		return (T) lookup (name, Object.class);
	}

	public <T> T lookup (final Class<? extends T> type) throws NamingException
	{
		return lookup (type.getName (), type);
	}

	public <T> T lookup (String name, final Class<? extends T> type) throws NamingException
	{
		log.trace ("lookup ({}, {})", name, type);
		if (name == null && type == null) throw new IllegalArgumentException ("Either JNDI name or type must be specified");
		if (name == null) name = type.getName ();

		Object obj = initialCtx.lookup (name);
		return (T) (type != null ? PortableRemoteObject.narrow (obj, type) : obj);
	}
}
